package com.mynews.activities.main.ui.classification;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;

import androidx.databinding.BindingAdapter;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModel;

import com.google.android.material.tabs.TabLayout;
import com.mynews.activities.App;
import com.mynews.activities.detail.DetailActivity;
import com.mynews.activities.view.PullingLayout;
import com.mynews.adapter.NewsAdapter;
import com.mynews.bean.NewsBean;
import com.mynews.databinding.FragmentClassificationBinding;
import com.mynews.utils.BmobApi;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class ClassificationVM extends ViewModel {
    public static String[] types=new String[]{"全部","娱乐","疫情","热点","生活","体育","科技","新时代","其他"};
    private static int nowPos=0;
    private static final List<NewsBean> data=new ArrayList<>();
    @SuppressLint("StaticFieldLeak")
    private static FragmentActivity fragmentActivity;
    @SuppressLint("StaticFieldLeak")
    private static FragmentClassificationBinding binding;
    public static int count=0;
    public void setBinding(FragmentClassificationBinding binding, FragmentActivity fragmentActivity) {
        ClassificationVM.binding=binding;
        ClassificationVM.fragmentActivity=fragmentActivity;
        binding.setAdp(new NewsAdapter(fragmentActivity,data));
        binding.classificationList.setOnItemClickListener((parent, view, position, id) -> {
            App.newsBean=data.get(position);
            fragmentActivity.runOnUiThread(() -> fragmentActivity.startActivity(new Intent(fragmentActivity, DetailActivity.class)));
        });
        refresh(null,"0");
    }
    @BindingAdapter("bindTab")
    public static void bindTab(TabLayout tabLayout, String[] types){
        for (String str :types) { tabLayout.addTab(tabLayout.newTab().setText(str)); }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                nowPos=tab.getPosition();
                refresh(null,"0");
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) { }
            @Override
            public void onTabReselected(TabLayout.Tab tab) { }
        });
    }
    private static void refresh(PullingLayout pullingLayout,String skip) {
        if (skip.equals("0")){
            data.clear();
        }
        String url;
        if (nowPos==0){
            url="https://api2.bmob.cn/1/classes/news?order=-createdAt&limit=10&skip="+skip;
        }else{
            url="https://api2.bmob.cn/1/classes/news?order=-createdAt&limit=10&skip="+skip+"&where="+ URLEncoder.encode("{\"type\":\""+types[nowPos]+"\"}");
        }
        BmobApi.get(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    assert response.body() != null;
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject jo = ja.getJSONObject(i);
                        data.add(new NewsBean(jo.getString("objectId"),jo.getString("title"),jo.getString("content"),jo.getString("ownerId"),jo.getString("updatedAt"),jo.getString("type"),null));
                    }
                    fragmentActivity.runOnUiThread(() -> {
                        binding.getAdp().notifyDataSetChanged();
                        if (pullingLayout!=null){
                            if (response.request().url().queryParameter("skip").equals("0")){
                                pullingLayout.refreshFinish(0);
                            }else {
                                pullingLayout.loadmoreFinish(0);
                            }
                        }
                        count=data.size();
                    });
                } catch (JSONException e) {e.printStackTrace();}
            }
        });
    }
    @BindingAdapter("bindPull")
    public static void bindPull(PullingLayout pullingLayout, ClassificationVM classificationVM){
        pullingLayout.setPullDownEnabled(true);
        pullingLayout.setOnRefreshListener(pullToRefreshLayout -> refresh(pullingLayout,"0"));

        pullingLayout.setPullUpEnabled(true);
        pullingLayout.setOnLoadMoreListener(pullToRefreshLayout -> refresh(pullingLayout,String.valueOf(count)));
    }
}